<template>
  <div class="login">
    <van-nav-bar title="登录" />

    <van-cell-group>
      <van-field
        v-model="mobile"
        required
        center
        label="手机号"
        placeholder="请输入手机号"
        :error-message="mobile_errmsg"
        @input="validate"
      />
      <van-field
        v-model="code"
        required
        label="验证码"
        placeholder="请输入验证码"
        :error-message="code_errmsg"
        @input="validate"
      >
        <template #button>
          <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div class="btn-wrap">
      <van-button type="info" @click="login">登录按钮</van-button>
      <van-button class="login-btn" type="primary" @click="getUserInfo">获取个人资料</van-button>
    </div>
  </div>
</template>

<script>
// 导入 axios 请求
import { reqLogin, reqSendCode, reqGetProfile } from '@/api/user'

// 导入 vuex
import { mapMutations } from 'vuex'

export default {
  naem: 'Login',

  data() {
    return {
      mobile: '13912345678',
      code: '246810',
      mobile_errmsg: '',
      code_errmsg: ''
    }
  },

  methods: {
    ...mapMutations('user', ['setTokenInfo']),

    // 发送验证码
    async sendCode() {
      try {
        await reqSendCode(this.mobile)
        this.$toast('验证码发送成功')
      } catch (e) {
        this.$toast(e.response.data.message)
      }
    },

    // 登录
    async login() {
      if (!this.validate()) return

      this.$toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景的点击
        overlay: true, // 显示遮罩
        duration: 0 // 展示时长，不限时间
      })

      try {
        const res = await reqLogin(this.mobile, this.code)
        this.setTokenInfo(res.data)
        this.$toast.success('登录成功')
        this.$router.push('/')
      } catch (e) {
        this.$toast.fail(e.response.data.message)
      }
    },

    // 表单验证
    validate() {
      if (this.mobile === '') {
        this.mobile_errmsg = '请输入手机号'
        return false
      }

      if (!/^1[3456789]\d{9}$/.test(this.mobile)) {
        this.mobile_errmsg = '请输入正确的手机号'
        return false
      }

      this.mobile_errmsg = ''

      if (this.code === '') {
        this.mobile_errmsg = '请输入验证码'
        return false
      }

      if (!/^\d{6}$/.test(this.code)) {
        this.mobile_errmsg = '请输入正确的验证码'
        return false
      }

      this.code_errmsg = ''

      return true
    },

    // 获取个人资料
    async getUserInfo() {
      const res = await reqGetProfile()
      console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
.btn-wrap {
  padding: 20px;
  .van-button {
    width: 100%;
    border-radius: 5px;
  }
}
}
</style>
